package cn.linjianhui.interview.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockABC {

    private static ReentrantLock lock = new ReentrantLock();
    private static Condition conditionA = lock.newCondition();
    private static Condition conditionB = lock.newCondition();
    private static Condition conditionC = lock.newCondition();
    private static int state = 0;

    public static void print(String name, int targetState, Condition current, Condition next) {
        for(int i = 0; i < 10; i++) {
            // 可重入锁，一个线程可以多次获取同一把锁
            lock.lock();
            try {
                if (state % 3 != targetState) current.await();
                System.out.println(Thread.currentThread().getName() + " : " + name);
                state++;
                next.signal();
            } catch (Exception e) {
                Thread.currentThread().interrupt();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(() -> print("A", 0, conditionA, conditionB)).start();
        new Thread(() -> print("B", 1, conditionB, conditionC)).start();
        new Thread(() -> print("C", 2, conditionC, conditionA)).start();
    }
}
